package com.xuxk.project.oauth.config;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xuxk.project.util.DESUtil;
import com.xuxk.project.util.JwtBaseInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 许孝康
 * @date 2020/7/29
 * @company 橙云科技有限公司
 */


@Component
public class JwtUtil {

    @Value("${oauth.token.oauthUser}")
    private String oauthUser ;

    /**
     * JWT验证
     * @param token 票据
     * @param secretKey 签名秘钥
     * @return
     */
    public DecodedJWT verifyJWT(String token,String secretKey){
        try {
            Algorithm algorithm = Algorithm.HMAC256(secretKey);
            //设置签发人
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(oauthUser)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt;
        } catch (JWTVerificationException e){
            return null;
        }
    }
    public String buildJWT(JwtBaseInfo info, String secretKey, long tokenExpireTime){

        //生成jwt
        Date now = new Date();
        Algorithm algo = Algorithm.HMAC256(secretKey);
        String token = JWT.create()
                .withIssuer(oauthUser)
                .withIssuedAt(now)
                .withExpiresAt(new Date(now.getTime() + tokenExpireTime))
                .withClaim(JwtBaseInfo.INFO, DESUtil.Encrytor(JSON.toJSONString(info),secretKey))
                .sign(algo);
        return token;
    }


}
